import axios from "axios";
import { profile } from "@depjs/storage";

let keys = new Map();
let controller = new AbortController();

// 请求拦截器
axios.interceptors.request.use(
    (config) => {
        if (profile.userName && profile.token) {
            config.headers.userName = profile.userName;
            config.headers.token = profile.token;
        }

        /**取消重复请求 限制同请求的时间间隔为100ms*/
        const { url, method, data } = config;
        if (method === "post") {
            const key =
                url.split("?")[0] + JSON.stringify(data) + profile.userName; // 请求地址和数据
            if (keys.has(key)) {
                //如果已经存在了，说明刚才请求过了，就要取消重复请求
                if (Date.now() - keys.get(key) < 100) {
                    // 两次同条件请求间隔必须在100ms以上
                    controller.abort(); // 取消请求
                } else {
                    keys.set(key, Date.now());
                    controller = new AbortController(); // 更新控制器
                }
            } else {
                keys.set(key, Date.now());
            }
        }

        config.url = "/api" + config.url;

        return config;
    },

    (err) => Promise.reject(err)
);

// 添加响应拦截器
axios.interceptors.response.use(
    // 响应成功时
    (res) => {
        return res.data;
    },

    (err) => Promise.reject(err)
);

export const request = (url, data = {}, method = "get") => {
    return new Promise((resolve, reject) => {
        let promise;

        if (method === "get") {
            promise = axios.get(`${url}?v=${Date.now()}`, { params: data });
        } else if (method === "post") {
            promise = axios.post(`${url}?v=${Date.now()}`, data, {
                signal: controller.signal,
            });
        }

        promise
            .then((res) => resolve(res))
            // .catch(err => reject(err))
            .catch((err) => console.log("err: ", err));
    });
};
